<template>
  <el-form
    v-if="getShow"
    ref="formSmsLogin"
    :model="loginData.loginForm"
    :rules="rules"
    class="login-form w-full"
    label-position="top"
    label-width="120px"
    size="large"
  >
    <el-row style="margin-right: -10px; margin-left: -10px" v-if="!isShowUserList">
      <!-- 标题 -->
      <div class="w-full">
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item>
            <LoginFormTitle style="width: 100%" />
          </el-form-item>
        </el-col>
        <!-- 手机号 -->
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item label="手机号码" prop="mobileNumber">
            <el-input
              v-model.trim="loginData.loginForm.mobileNumber"
              :placeholder="t('login.mobileNumberPlaceholder')"
              :prefix-icon="iconCellphone"
            />
          </el-form-item>
        </el-col>
        <!-- 验证码 -->
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item label="验证码" prop="code">
            <el-row :gutter="5" justify="space-between" style="width: 100%">
              <el-col :span="24">
                <el-input
                  v-model.trim="loginData.loginForm.code"
                  :placeholder="t('login.codePlaceholder')"
                  :prefix-icon="iconCircleCheck"
                >
                  <template #append>
                    <span
                      v-if="mobileCodeTimer <= 0"
                      class="text-#172b4d"
                      style="cursor: pointer"
                      @click="getCode"
                    >
                      {{ t('login.getSmsCode') }}
                    </span>
                    <span v-if="mobileCodeTimer > 0" style="cursor: pointer">
                      {{ mobileCodeTimer }}秒后可重新获取
                    </span>
                  </template>
                </el-input>
              </el-col>
            </el-row>
          </el-form-item>
        </el-col>
        <!-- 登录按钮 / 返回按钮 -->
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item>
            <XButton
              :loading="loginLoading"
              :title="t('login.login')"
              class="w-[100%] login_btn"
              type="primary"
              @click="signIn()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item>
            <XButton
              :loading="loginLoading"
              :title="t('login.backLogin')"
              class="w-[100%]"
              @click="handleBackLogin()"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="padding-right: 10px; padding-left: 10px">
          <el-form-item>
            <XButton :title="t('login.btnWeChat')" class="w-[100%]" @click="weChatLogin" />
          </el-form-item>
        </el-col>
        <Verify
          ref="verify"
          :captchaType="captchaType"
          :imgSize="{ width: '400px', height: '200px' }"
          mode="pop"
          @success="getSmsCode"
        />
      </div>
    </el-row>
    <div
      class="w-full"
      v-show="isShowUserList"
      style="
        border: 1px solid #e4e7ed;
        padding: 20px;
        padding-bottom: 0px;
        box-sizing: border-box;
        border-radius: 4px;
      "
    >
      <el-col :span="24" class="mb-10px text-center text-22px font-bold text-#172b4d">
        该用户有{{ userList.length }}个企业
      </el-col>
      <el-col :span="24" class="mb-20px text-center text-14px text-#666">
        请选择要登录的企业
      </el-col>
      <el-scrollbar wrap-style="max-height: 238px;">
        <el-card
          body-style="padding: 0px 16px; display: flex; align-items: center; justify-content: space-between;"
          v-for="item in userList"
          :key="item.userId"
          shadow="naver"
          :class="[
            { enterIcon: item.tenantInfo.status == 0 },
            { disabledCard: item.tenantInfo.status == 1 },
            'mb-10px'
          ]"
        >
          <div>
            <el-col :span="24">
              <p class="my-8px text-18px font-600">{{ item.tenantInfo.name }}</p>
            </el-col>
            <el-col :span="24">
              <p class="my-8px text-14px text-#666"><label>账号昵称: </label>{{ item.nickname }}</p>
            </el-col>
          </div>
          <div>
            <span
              @click="userLogin(item)"
              v-if="item.tenantInfo.status == 0"
              class="relative z-2 flex cursor-pointer items-center text-12px"
            >
              <Icon class="mr-4px" size="16" icon="fa-solid:sign-out-alt" />
              进入
            </span>
            <el-tag v-else type="danger" size="small">已过期</el-tag>
          </div>
        </el-card>
      </el-scrollbar>

      <el-col :span="24" class="mt-40px">
        <el-form-item>
          <XButton
            :loading="loginLoading"
            title="登录其他账号"
            class="w-[100%]"
            @click="handleBackLogin()"
          />
        </el-form-item>
      </el-col>
    </div>
  </el-form>
</template>
<script lang="ts" setup>
import type { RouteLocationNormalizedLoaded } from 'vue-router'

import { useIcon } from '@/hooks/web/useIcon'
import { setTenantId, setTenantSign, setToken } from '@/utils/auth'
import { usePermissionStore } from '@/store/modules/permission'
import {
  getTenantIdByName,
  sendSmsCode,
  smsLogin,
  smsLoginGetUserList,
  smsUserIdLogin
} from '@/api/login'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useFormValid, useLoginState } from './useLogin'
import { ElLoading } from 'element-plus'

defineOptions({ name: 'MobileForm' })

const props = defineProps({
  agree: {
    type: Boolean,
    default: () => true
  }
})

const { t } = useI18n()
const message = useMessage()
const permissionStore = usePermissionStore()
const { currentRoute, push } = useRouter()
const formSmsLogin = ref()
const loginLoading = ref(false)
const iconHouse = useIcon({ icon: 'ep:house' })
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { validForm } = useFormValid(formSmsLogin)
const { handleBackLogin, getLoginState, setLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE)

const tenantStatusMap = {
  0: {
    type: 'success',
    text: '正常'
  },
  1: {
    type: 'danger',
    text: '停用'
  }
}

const rules = {
  tenantName: [required],
  mobileNumber: [required],
  code: [required]
}
const loginData = reactive({
  codeImg: '',
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  token: '',
  loading: {
    signIn: false
  },
  loginForm: {
    uuid: '',
    tenantName: '',
    mobileNumber: '',
    code: ''
  }
})
const smsVO = reactive({
  smsCode: {
    mobile: '',
    scene: 21
  },
  loginSms: {
    mobile: '',
    code: ''
  }
})

const verify = ref()
const captchaType = ref('blockPuzzle') // blockPuzzle 滑块 clickWord 点击文字
// 获取验证码
const getCode = async () => {
  if (!props.agree) {
    message.error('请先同意用户使用协议和个人信息保护政策')
    return
  }
  // 情况一，未开启：则直接登录
  if (loginData.captchaEnable === 'false') {
    await signIn({})
  } else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}

const mobileCodeTimer = ref(0)
const redirect = ref<string>('')
const getSmsCode = async () => {
  smsVO.smsCode.mobile = loginData.loginForm.mobileNumber
  await sendSmsCode(smsVO.smsCode).then(async () => {
    message.success(t('login.SmsSendMsg'))
    // 设置倒计时
    mobileCodeTimer.value = 60
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer)
      }
    }, 1000)
  })
}
watch(
  () => currentRoute.value,
  (route: RouteLocationNormalizedLoaded) => {
    redirect.value = route?.query?.redirect as string
  },
  {
    immediate: true
  }
)

// get-user-list 第三步

// 获取租户 ID
const getTenantId = async () => {
  if (loginData.tenantEnable === 'true') {
    const res = await getTenantIdByName(loginData.loginForm.tenantName)
    setTenantId(res ? res.id : null)
    setTenantSign(res ? res.sign : null)
  }
}

const isShowUserList = ref(false)
const userList = ref([])
// 登录
const signIn = async () => {
  const data = await validForm()
  if (!data) return
  ElLoading.service({
    lock: true,
    text: '正在加载系统中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  loginLoading.value = true
  smsVO.loginSms.mobile = loginData.loginForm.mobileNumber
  smsVO.loginSms.code = loginData.loginForm.code
  await smsLoginGetUserList(smsVO.loginSms)
    .then(async (res) => {
      if (res != null) {
        isShowUserList.value = true
        userList.value = res
      }
    })
    .catch(() => {})
    .finally(() => {
      loginLoading.value = false
      setTimeout(() => {
        const loadingInstance = ElLoading.service()
        loadingInstance.close()
      }, 400)
    })
}

const userLogin = async (user) => {
  if (!props.agree) {
    message.error('请先同意用户使用协议和个人信息保护政策')
    return
  }
  if (user.tenantInfo.status == 1) {
    message.error('该企业已停用')
    return
  }

  setTenantId(user.tenantInfo.id || null)
  setTenantSign(user.tenantInfo.sign || null)
  ElLoading.service({
    lock: true,
    text: '正在加载系统中...',
    background: 'rgba(0, 0, 0, 0.7)',
    closed: 1500
  })
  loginLoading.value = true
  await smsUserIdLogin({
    userId: user.userId
  })
    .then(async (res) => {
      setToken(res)
      if (!redirect.value) {
        redirect.value = '/'
      }
      push({ path: redirect.value || permissionStore.addRouters[0].path })
    })
    .catch(() => {})
    .finally(() => {
      loginLoading.value = false
      setTimeout(() => {
        const loadingInstance = ElLoading.service()
        loadingInstance.close()
      }, 400)
    })
}

/*企业微信登录*/
const weChatLogin = () => {
  setLoginState(LoginStateEnum.WECHAT_LOGIN)
}
</script>

<style lang="scss" scoped>
:deep(.anticon) {
  &:hover {
    color: var(--el-color-primary) !important;
  }
}

.smsbtn {
  margin-top: 33px;
}

.enterIcon {
  background: none;
  text-transform: uppercase;
  font-weight: bold;
  position: relative;
  outline: none;
  box-sizing: border-box;
}

.enterIcon::before,
.enterIcon::after {
  box-sizing: inherit;
  position: absolute;
  content: '';
  border: 2px solid transparent;
  width: 0;
  height: 0;
}

.enterIcon::after {
  bottom: 0;
  right: 0;
}

.enterIcon::before {
  top: 0;
  left: 0;
}

.enterIcon:hover {
  box-shadow: var(--el-box-shadow-light);
  // span {
  //   color: var(--el-color-primary);
  // }
}

.enterIcon:hover::before,
.enterIcon:hover::after {
  width: 100%;
  height: 100%;
}

.enterIcon:hover::before {
  border-top-color: var(--el-color-primary);
  border-right-color: var(--el-color-primary);
  transition:
    width 0.3s ease-out,
    height 0.3s ease-out 0.3s;
}

.enterIcon:hover::after {
  border-bottom-color: var(--el-color-primary);
  border-left-color: var(--el-color-primary);
  transition:
    border-color 0s ease-out 0.6s,
    width 0.3s ease-out 0.6s,
    height 0.3s ease-out 1s;
}
.disabledCard {
  color: #a8abb2;
  cursor: not-allowed;
  p {
    color: #a8abb2;
  }
}

:deep(.el-input-group__append) {
  border-radius: 40px !important;
}
:deep(.el-input__wrapper) {
  border-radius: 40px !important;
}

@media screen and (min-width: 375px) and (max-width: 450px) {
  .login_btn {
    margin-bottom: 6px;
    margin-top: 6px;
  }
}
</style>
